package com.gaowl.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaowl.common.utils.PageUtils;
import com.gaowl.common.utils.Query;

import com.gaowl.gulimall.product.dao.CategoryDao;
import com.gaowl.gulimall.product.entity.CategoryEntity;
import com.gaowl.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity>
        implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        // 2.组装为父子结构
        // 找到一级分类
        List<CategoryEntity> level1Menus = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)  // 一级分类的父id为0
                .peek(menu -> menu.setChildren(getChildren(menu, categoryEntityList)))   // 设置子类别
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))  // 根据sort字段，从小到大排序
                .collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 获取当前菜单的所有子分类
     * @param root 当前类别
     * @param all 所有类别
     * @return 所有子分类
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))   // 当前类别的父类别 为 root的类别
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, all))) // 递归设置其子类别
                .sorted((menu1,menu2)->{    // 排序，同时需要避免排序字段为空
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());

        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO:删除前，需检查当前要删除的类别，是否被其他类别所引用
        baseMapper.deleteBatchIds(asList);
    }


    /**
     * 根据节点id寻找 从根节点到当前节点的路径
     * @param catelogId 节点的id
     * @return 节点路径，[父/子/孙]
     */
    @Override
    public Long[] findCatelogPathById(Long catelogId) {
        ArrayList<Long> path = new ArrayList<>();
        findParentPath(catelogId, path);
        Collections.reverse(path);   // 225,13,2  --> 2,13,225

        return path.toArray(new Long[path.size()]);   // 集合转换为数组
    }
    private List<Long> findParentPath(Long catelogId, ArrayList<Long> path){
        path.add(catelogId);  // 一级级地找到父节点
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid()!=0){
            findParentPath(categoryEntity.getParentCid(), path);  // 当前节点的父节点id: categoryEntity.getParentCid()
        }
        return path;
    }

}